﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ZiChen.SoXunLeiPan.Common;
using ZiChen.SoXunLeiPan.ViewModel.Result;

namespace ZiChen.SoXunLeiPan.Service
{
    public class UpdateCheckerService
    {
        private readonly IHttpService _httpService = App.Services.GetService<IHttpService>();

        public bool _isUpdate = false;
        public UpdateInfo _updateInfo { get; set; }
        // 当前应用版本
        private Version _currentVersion;

        public UpdateCheckerService()
        {
            InitializeCurrentVersion();
        }

        /// <summary>
        /// 初始化当前应用版本
        /// </summary>
        private void InitializeCurrentVersion()
        {
            var versionString = AppInfo.VersionString;
            _currentVersion = Version.Parse(versionString);
        }

        /// <summary>
        /// 检查是否有更新
        /// </summary>
        /// <returns>更新信息，如果有更新则返回，否则返回null</returns>
        public async Task<UnifyResult<UpdateInfo>> CheckForUpdatesAsync()
        {
           
            try
            {
                var dit = new Dictionary<string, object>
                {
                    { "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() },
                    { "nonce", Guid.NewGuid().ToString() }
                };
                var secret = await SecureStorage.GetAsync("sign_secret");
                string sign = UrlSignTopRequest.Sign(dit, secret);
                dit["sign"] = sign;
                var queryString = string.Join("&", dit.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value.ToString())}"));
                var result = await _httpService.GetAsync<UnifyResult<UpdateInfo>>("api/app/version?" + queryString, "ApiClient");

                if (result.Data != null)
                {
                    // 解析最新版本号
                    if (Version.TryParse(result.Data.Version, out var latestVersion))
                    {
                        // 比较版本号
                        if (latestVersion > _currentVersion)
                        {
                            _isUpdate = true;
                            _updateInfo = result.Data;
                            return result.Data;
                        }
                        else
                        {
                            _isUpdate = false;
                            return new UnifyResult<UpdateInfo> { Code = ResultCode.ResultError, Msg = "当前已是最新版本",Data = null };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }

            return new UnifyResult<UpdateInfo> { Code = ResultCode.ResultError, Msg = "未知错误", Data = null }; ;
        }

        /// <summary>
        /// 执行更新操作
        /// </summary>
        /// <param name="updateInfo">更新信息</param>
        public async Task PerformUpdateAsync(UpdateInfo updateInfo)
        {
            if (updateInfo == null)
                return;

            // 根据不同平台执行不同的更新逻辑
#if ANDROID
            // Android平台可以直接打开下载链接或应用商店
            await Launcher.OpenAsync(new Uri(updateInfo.AndroidDownloadUrl));
#elif IOS
            // iOS平台通常引导用户到App Store
            await Launcher.OpenAsync(new Uri(updateInfo.IosDownloadUrl));
#elif WINDOWS
            // Windows平台可以打开MSIX包下载链接
            await Launcher.OpenAsync(new Uri(updateInfo.WindowsDownloadUrl));
#else
            // 其他平台
            await Launcher.OpenAsync(new Uri(updateInfo.DefaultDownloadUrl));
#endif
        }
    }
    /// <summary>
    /// 更新信息模型
    /// </summary>
    public class UpdateInfo
    {
        public string Version { get; set; }
        public string Description { get; set; }
        public string ReleaseDate { get; set; }
        public string AndroidDownloadUrl { get; set; }
        public string IosDownloadUrl { get; set; }
        public string WindowsDownloadUrl { get; set; }
        public string DefaultDownloadUrl { get; set; }
    }
}
